package com.syni.mdd.sjb.common.datatreaure.service.impl.databank;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DankHomePageStatistics;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppNews;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppServices;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DxshAppUserChannel;
import com.syni.mdd.sjb.common.component.utils.common.spring.ApplicationContextHolder;
import com.syni.mdd.sjb.common.component.utils.common.thread.ThreadPoolUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mdd.sjb.common.dxshapp.CommonPushToDsxhAppDto;
import com.syni.mdd.sjb.common.datatreaure.constants.Constants;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.bo.apiNews.MtNewsBo;
import com.syni.mdd.sjb.common.datatreaure.entity.bo.dataBankBusiness.CdpUtilsBo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.dataBankBusiness.MerchantApplicationVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.dataBankBusiness.NewDetailParamsRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rp.databBankCommon.HomePageDataRpVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.databank.DataBankCommonVo;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.databank.UnifiedPushVo;
import com.syni.mdd.sjb.common.datatreaure.handler.news.MarketingRealityHandler;
import com.syni.mdd.sjb.common.datatreaure.handler.news.NewsHandler;
import com.syni.mdd.sjb.common.datatreaure.handler.news.OrderDynamicsHandler;
import com.syni.mdd.sjb.common.datatreaure.handler.news.OtherNewsHandler;
import com.syni.mdd.sjb.common.datatreaure.listen.appNews.AppNewsSwitchEvent;
import com.syni.mdd.sjb.common.datatreaure.service.*;
import com.syni.mdd.sjb.common.datatreaure.service.databank.DataBankCommonService;
import com.syni.mdd.sjb.common.datatreaure.utils.CDPUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Service
@Log4j2
public class DataBankCommonServiceImpl implements DataBankCommonService {

    public final static Map<Integer, NewsHandler> NEWS_HANDLER_MAP = new HashMap(){{
        put(Constants.DXSH_APP_NEW_ORDER_STATUS,new OrderDynamicsHandler());
        put(Constants.DXSH_APP_NEW_MARKET_REALITY,new MarketingRealityHandler());
        put(Constants.DXSH_APP_NEW_ORTHER,new OtherNewsHandler());
    }};

    @Autowired
    DankHomePageStatisticsService dankHomePageStatisticsService;

    @Autowired
    DxshAppServicesService dxshAppServicesService;

    @Autowired
    DankApplicationService dankApplicationService;

    @Autowired
    DankMerchantsApplicationService dankMerchantsApplicationService;

    @Autowired
    DxshAppNewsService dxshAppNewsService;

    @Autowired
    UserService userService;

    @Autowired
    DankMerchantsDefBusinessService dankMerchantsDefBusinessService;

    @Autowired
    DxshAppUserChannelService dxshAppUserChannelService;

    @Override
    public Map<String, Object> homePageData(DataBankCommonVo dataBankCommonVo) {
        HomePageDataRpVo homePageDataRpVo = new HomePageDataRpVo();
        //统计面板
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DankHomePageStatistics.USER_ID,dataBankCommonVo.getUserId());
        List<DankHomePageStatistics> dankHomePageStatisticsList = dankHomePageStatisticsService.list(queryWrapper);
        DankHomePageStatistics dankHomePageStatistics;
        if(CollectionUtils.isEmpty(dankHomePageStatisticsList)){
            dankHomePageStatistics = new DankHomePageStatistics();
            dankHomePageStatistics.setUserId(dataBankCommonVo.getUserId());
            dankHomePageStatisticsService.save(dankHomePageStatistics);
            dankHomePageStatistics = dankHomePageStatisticsService.getById(dankHomePageStatistics.getId());
        }else {
            dankHomePageStatistics = dankHomePageStatisticsList.get(0);
        }
        HomePageDataRpVo.MarketingKanban marketingKanban = BeanUtils.copyProperties(dankHomePageStatistics,HomePageDataRpVo.MarketingKanban.class);
        homePageDataRpVo.setMarketingKanban(marketingKanban);
        HomePageDataRpVo.CustomerKanban customerKanban = BeanUtils.copyProperties(dankHomePageStatistics,HomePageDataRpVo.CustomerKanban.class);
        homePageDataRpVo.setCustomerKanban(customerKanban);
        HomePageDataRpVo.BusinessKanban businessKanban = BeanUtils.copyProperties(dankHomePageStatistics,HomePageDataRpVo.BusinessKanban.class);
        homePageDataRpVo.setBusinessKanban(businessKanban);
        CDPDocking(dataBankCommonVo,homePageDataRpVo);

        //初始化配置我的应用
        dankHomePageStatisticsService.initMyService(dataBankCommonVo.getUserId());

        //我的应用
        List<MerchantApplicationVo> merchantApp = dankMerchantsApplicationService.getMerchantApp(dataBankCommonVo.getUserId());
        homePageDataRpVo.setApplications(BeanUtils.copyList(merchantApp,HomePageDataRpVo.Application.class));

        //推荐服务
        List<DxshAppServices> dxshAppServices = dxshAppServicesService.getRecommendService();
        if(CollectionUtils.isNotEmpty(dxshAppServices)){
            homePageDataRpVo.setRecommendServices(BeanUtils.copyList(dxshAppServices,HomePageDataRpVo.RecommendService.class));
        }
        //默认的消息条数
        Integer businessId = dankMerchantsDefBusinessService.getChooseBusinessId(dataBankCommonVo.getUserId());
        if(businessId != null){
            homePageDataRpVo.setReceMessagesNum(homePageDataRpVo.getReceMessagesNum() + dxshAppNewsService.getUserNoReadMddMessageCount(dataBankCommonVo.getUserId(),businessId));
        }
        //统计小程序
        homePageDataRpVo.setReceMessagesNum(homePageDataRpVo.getReceMessagesNum() + dxshAppNewsService.getUserNoReadMinAppMessageCount(dataBankCommonVo.getUserId()));
        //默认开启消息推送
        ApplicationContextHolder.getApplicationContext().
                publishEvent(new AppNewsSwitchEvent("initNewSwitch",dataBankCommonVo.getUserId()));//默认开启消息推送
        return ResultMapHelper.success(homePageDataRpVo, ResultMsg.MSG_GET_SUCCESS);
    }

    private void CDPDocking(DataBankCommonVo dataBankCommonVo,HomePageDataRpVo homePageDataRpVo){
        Date nowTime = new Date();
        homePageDataRpVo.getMarketingKanban().setMarketKbDeadline(DateTimeUtils.converDateToLocalDateTime(nowTime));
        homePageDataRpVo.getCustomerKanban().setCustomerKbDeadline(DateTimeUtils.converDateToLocalDateTime(nowTime));
        homePageDataRpVo.getBusinessKanban().setBusinessKbDeadline(DateTimeUtils.converDateToLocalDateTime(nowTime));
        String totalDate = DateTimeUtils.converDateToString(nowTime, DateTimeUtils.DATE_PATTERN_DAY);
        String startDate = DateTimeUtils.converDateToString(DateTimeUtils.addMonth(nowTime, -120), DateTimeUtils.DATE_PATTERN_DAY);
        CountDownLatch countDownLatch = new CountDownLatch(9);
        CdpUtilsBo cdpUtilsBo = new CdpUtilsBo();
        //TODO 今日营销看板的数值
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.activityActivityTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate);
            homePageDataRpVo.getMarketingKanban().setMarketKbActivitiesNum(cdpUtilsBo.getActivityQuantity());
            homePageDataRpVo.getMarketingKanban().setMarketKbTotalParticipants(cdpUtilsBo.getJoinNum());
            homePageDataRpVo.getMarketingKanban().setMarketKbArrivalsNum(cdpUtilsBo.getNewNum());
            countDownLatch.countDown();
        });

        //TODO 今日客户看板的数值
        //设置潜客数
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.userPotentialUserTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate);
            homePageDataRpVo.getCustomerKanban().setCustomerKbNewPotentialCustomers(cdpUtilsBo.getPotentialUserQuantity());
            homePageDataRpVo.getCustomerKanban().setCustomerKbPcPotentialRevenue(cdpUtilsBo.getPotentialRevenue());
            countDownLatch.countDown();

        });

        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.userCustomerTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate);
            homePageDataRpVo.getCustomerKanban().setCustomerKbNewCustomersNum(cdpUtilsBo.getCustomerQuantity());
            homePageDataRpVo.getCustomerKanban().setCustomerKbActualRevenue(cdpUtilsBo.getRevenue());
            countDownLatch.countDown();

        });
//        //设置客户数
//        CDPUtils.userCustomerTotal(cdpUtilsBo,userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()),totalDate);
//        homePageDataRpVo.getCustomerKanban().setCustomerKbNewCustomersNum(cdpUtilsBo.getCustomerQuantity());
//        homePageDataRpVo.getCustomerKanban().setCustomerKbActualRevenue(cdpUtilsBo.getRevenue());
        //设置会员数
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.userMemberTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate);
            homePageDataRpVo.getCustomerKanban().setCustomerKbNewMembersNum(cdpUtilsBo.getMemberQuantity());
            homePageDataRpVo.getCustomerKanban().setCustomerKbMPotentialRevenue(cdpUtilsBo.getMemberPotentialRevenue());
            countDownLatch.countDown();

        });
//        CDPUtils.userMemberTotal(cdpUtilsBo,userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()),totalDate);
//        homePageDataRpVo.getCustomerKanban().setCustomerKbNewMembersNum(cdpUtilsBo.getMemberQuantity());
//        homePageDataRpVo.getCustomerKanban().setCustomerKbMPotentialRevenue(cdpUtilsBo.getMemberPotentialRevenue());
        //设置复购数

        //TODO 今日经营看板的数值
        //待处理订单数
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.orderPendingOrderTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate);
            homePageDataRpVo.getBusinessKanban().setBusinessKbOrdersProcessedNum(cdpUtilsBo.getBusinessKbOrdersProcessedNum());
            countDownLatch.countDown();

        });
//        CDPUtils.orderPendingOrderTotal(cdpUtilsBo,userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()),totalDate);
//        homePageDataRpVo.getBusinessKanban().setBusinessKbOrdersProcessedNum(cdpUtilsBo.getBusinessKbOrdersProcessedNum());
        //总营收，总订单
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.orderOrderTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), "", totalDate);
            homePageDataRpVo.getBusinessKanban().setBusinessKbTotalRevenue(cdpUtilsBo.getTotalAmount());
            homePageDataRpVo.getBusinessKanban().setBusinessKbTotalOrder(cdpUtilsBo.getOrderQuantity());
            countDownLatch.countDown();

        });
//        CDPUtils.orderOrderTotal(cdpUtilsBo,userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()),"",totalDate);
//        homePageDataRpVo.getBusinessKanban().setBusinessKbTotalRevenue(cdpUtilsBo.getTotalAmount());
//        homePageDataRpVo.getBusinessKanban().setBusinessKbTotalOrder(cdpUtilsBo.getOrderQuantity());
        //新增营收，新增订单
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.orderOrderTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate, totalDate);
            homePageDataRpVo.getBusinessKanban().setBusinessKbNewRevenue(cdpUtilsBo.getTotalAmount());
            homePageDataRpVo.getBusinessKanban().setBusinessKbNewOrdersNum(cdpUtilsBo.getOrderQuantity());
            countDownLatch.countDown();

        });
//        CDPUtils.orderOrderTotal(cdpUtilsBo,userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()),totalDate,totalDate);
//        homePageDataRpVo.getBusinessKanban().setBusinessKbNewRevenue(cdpUtilsBo.getTotalAmount());
//        homePageDataRpVo.getBusinessKanban().setBusinessKbNewOrdersNum(cdpUtilsBo.getOrderQuantity());
        //浏览量和转化率
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.userAccessUserTotal(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate, totalDate);
            homePageDataRpVo.getBusinessKanban().setBusinessKbNewVisitNum(cdpUtilsBo.getUserQuantity());
            countDownLatch.countDown();

        });
//        CDPUtils.userAccessUserTotal(cdpUtilsBo,userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()),totalDate,totalDate);
//        homePageDataRpVo.getBusinessKanban().setBusinessKbNewVisitNum(cdpUtilsBo.getUserQuantity());
        ThreadPoolUtils.getExecutorService().submit(() -> {
            CDPUtils.orderPayConversionRate(cdpUtilsBo, userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()), totalDate, totalDate);
            homePageDataRpVo.getBusinessKanban().setBusinessKbConversionRate(ArithUtil.round(cdpUtilsBo.getPayRate() * 100, 2) + "%");
            countDownLatch.countDown();

        });
        try {
            countDownLatch.await(3000, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
//        CDPUtils.orderPayConversionRate(cdpUtilsBo,userService.getAccountIdByUserMap(dataBankCommonVo.getUserId()),totalDate,totalDate);
//        homePageDataRpVo.getBusinessKanban().setBusinessKbConversionRate(ArithUtil.round(cdpUtilsBo.getPayRate() * 100,2) + "%");
    }

    @Override
    public Map<String, Object> newDetailParams(Integer newId) {
        NewDetailParamsRpVo newDetailParamsRpVo = new NewDetailParamsRpVo();
        DxshAppNews dxshAppNews = dxshAppNewsService.getById(newId);
        if(dxshAppNews == null){
            return ResultMapHelper.success(newDetailParamsRpVo,ResultMsg.MSG_GET_SUCCESS);
        }
//        if(dxshAppNews.getType() == Constants.CODE_TYPE_MDD_RECE){
////
////        }
        this.handleNesDetail(dxshAppNews,newDetailParamsRpVo);
        return ResultMapHelper.success(newDetailParamsRpVo,ResultMsg.MSG_GET_SUCCESS);
    }

    public void handleNesDetail(DxshAppNews dxshAppNews,NewDetailParamsRpVo newDetailParamsRpVo) {
        newDetailParamsRpVo.setMessageType(dxshAppNews.getMessageType());
        newDetailParamsRpVo.setMessageSecondType(dxshAppNews.getMessageSecondType());
        try {
            if(NEWS_HANDLER_MAP.containsKey(dxshAppNews.getMessageType())){
                NEWS_HANDLER_MAP.get(dxshAppNews.getMessageType()).handle(dxshAppNews,newDetailParamsRpVo);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    @Override
    public Map<String, Object> unifiedPush(UnifiedPushVo unifiedPushVo) {
        final int YJGJ_TYPE = 2;
        log.info("收到通知的参数：{}" + JSON.toJSONString(unifiedPushVo));
        if(unifiedPushVo.getChannel() == YJGJ_TYPE){
            MtNewsBo mtNewsBo = JSON.parseObject(unifiedPushVo.getData(),MtNewsBo.class);
            String accountId = mtNewsBo.getAccountId();
            Integer userId = userService.getUserIdByAccountIdMap(accountId);
            CommonPushToDsxhAppDto commonPushToDsxhAppDto = new CommonPushToDsxhAppDto();
            commonPushToDsxhAppDto.setType(Constants.APP_NEWS_MT_SMART);
            commonPushToDsxhAppDto.setUserId(userId);
            commonPushToDsxhAppDto.setMainTitle("营销实况");
            commonPushToDsxhAppDto.setMessageType(Constants.DXSH_APP_NEW_MARKET_REALITY);
            commonPushToDsxhAppDto.setMessageSecondType(Constants.DXSH_APP_NEW_MARKET_REALITY_TYPE);
            commonPushToDsxhAppDto.setBusinessId(mtNewsBo.getBusinessId());
            commonPushToDsxhAppDto.setContent(JSON.toJSONString(mtNewsBo));
            if(StringUtils.isNotBlank(mtNewsBo.getSend_type())) {
                if (mtNewsBo.getSend_type().equals(MtNewsBo.SEND_TYPE_START)) {
                    commonPushToDsxhAppDto.setAlert(String.format(MtNewsBo.SEND_TYPE_START_ALERT, mtNewsBo.getActivityName(), mtNewsBo.getLaterMin()));
                    commonPushToDsxhAppDto.setDescribes(MtNewsBo.SEND_TYPE_START_DESC);
                } else if (mtNewsBo.getSend_type().equals(MtNewsBo.SEND_TYPE_END)) {
                    commonPushToDsxhAppDto.setAlert(MtNewsBo.SEND_TYPE_END_ALERT);
                    commonPushToDsxhAppDto.setDescribes(MtNewsBo.SEND_TYPE_END_DESC);
                } else if (mtNewsBo.getSend_type().equals(MtNewsBo.PRIZE_TYPE_OVER)) {
                    commonPushToDsxhAppDto.setAlert(String.format(MtNewsBo.PRIZE_TYPE_OVER_ALERT, mtNewsBo.getPrizeName(),
                            mtNewsBo.getPrizeAllNum(), mtNewsBo.getActivityName()));
                    commonPushToDsxhAppDto.setDescribes(MtNewsBo.PRIZE_TYPE_OVER_DESC);
                }
            }
            dxshAppNewsService.commonPushToDsxhApp_v2(commonPushToDsxhAppDto);
        }
        return ResultMapHelper.success(new HashMap<>(),ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> synchronizeData() {
        dxshAppUserChannelService.syncDxshappCompMe();
        return ResultMapHelper.success();
    }

    public Map<String, Object> synchronizeDxshAppNews() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DxshAppNews.TYPE, Constants.APP_NEWS_MINAPP);
        List<DxshAppNews> dxshAppNews = dxshAppNewsService.list(queryWrapper);
        List<DxshAppNews> updateNews = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(dxshAppNews)){
            for(DxshAppNews dx : dxshAppNews){
                try {
                    if(StringUtils.isEmpty(dx.getStoreId())){
                        //先看content有没有
                        if(StringUtils.isNotBlank(dx.getContent())) {
                            JSONObject jsonObject = JSON.parseObject(dx.getContent());
                            if (jsonObject.containsKey("storeId")) {
                                dx.setStoreId(jsonObject.getString("storeId"));
                                updateNews.add(dx);
                                continue;
                            }
                        }
                        //再看jumpto有没有
//                    if(jsonObject.containsKey("jumpTo")){
//                        String jumpTo = jsonObject.getString("jumpTo");
//                        if(jumpTo.indexOf("storeId") != -1){
//
//                        }
//                    }
                        //看用户和店铺
                        if(dx.getBusinessId() != null){
                            DxshAppUserChannel dxshAppUserChannel = dxshAppUserChannelService.getDxshChannelByBusinessIdAndChannel(dx.getBusinessId(),DxshAppUserChannelService.CHANNEL_MINAPP);
                            if(dxshAppUserChannel != null && StringUtils.isNotBlank(dxshAppUserChannel.getStoreId())
                                    && dxshAppUserChannel.getUserId().equals(dx.getUserId())){
                                dx.setStoreId(dxshAppUserChannel.getStoreId());
                                updateNews.add(dx);
                                continue;
                            }
                        }
                        //看用户
                        if(dx.getUserId() != null){
                            List<DxshAppUserChannel> dxshAppUserChannel = dxshAppUserChannelService.getDxshChannelByUserIdAndChannel(dx.getUserId(), DxshAppUserChannelService.CHANNEL_MINAPP);
                            if(CollectionUtils.isNotEmpty(dxshAppUserChannel) && dxshAppUserChannel.size() == 1){
                                dx.setStoreId(dxshAppUserChannel.get(0).getStoreId());
                                updateNews.add(dx);
                                continue;
                            }
                        }
                    }
                }catch (Exception e){
                    log.error(e.getMessage(),e);
                }
            }
        }
        if(updateNews.size() > 0){
            dxshAppNewsService.updateBatchById(updateNews);
        }
        return ResultMapHelper.success();
    }
}
